home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2453 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointer Conversion
  5. Date: 21 Jan 1996 12:42:20 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4dttts$b70@umbc9.umbc.edu>
  8. References: <4ds4jq$fo4@su3.in.net>
  9. NNTP-Posting-Host: umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Sam Pounds <poundss@in.net> wrote:
  13. |> I am having a problem with a "string concatenate" function.
  14. |> When I compile my little program it works, but I get a
  15. |> "suspicious pointer" conversion warning. The function is
  16. |> below and I call it with two strings that I want to concatenate.
  17. |> 
  18. |> char *my_strcat(const char *a, const char *b)
  19. |> {
  20. |>     char done[1024];
  21. |>     char *p = done;
  22. |> 
  23. |>     while (*a)
  24. |>       *p++ = *a++;
  25. |>     while (*b)
  26. |>       *p++ = *b++;
  27. |>     *p = '\0';
  28. |>     return done; /* this is the suspicious pointer conversion error */
  29. |> }
  30. |> 
  31. |> I'm sure someone can explain this to me.
  32. |> Thanks in advance.
  33.  
  34. First of all your function has different semantics from strcat() which
  35. may or may not be what you intended. In the <string.h> version only 'b'
  36. is const and 'a' is actually the string things are added onto. Now
  37. Everything looks pretty good up to the point where you return 'done'.
  38. No matter how similar in semantics pointers and arrays can be used
  39. they are not the same type. Pointers can be returned and arrays cannot.
  40. This is because returning an array is really returning a pointer to
  41. the first element, but the array is a local variable so this space
  42. goes away after the function ends.
  43.  
  44. What you need is to either make 'done' a static variable and have the
  45. calling function handle memory allocation, or else allocate the space
  46. inside of my_strcat() and return a legally allocated block of memory.
  47. -- 
  48. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  49.  
  50. Jonas J. Schlein  (schlein@gl.umbc.edu)
  51.